<template>
  <div class="hawkContent">
    <!-- 面包屑 -->
    <hawk-breadcrumb></hawk-breadcrumb>
    <!-- 搜索/添加 -->
    <el-row :gutter="20" style="padding-left: 20px">
      <el-col :span="3">
        <el-input placeholder="请输入名称搜索" v-model="queryInfo.query.name">
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="hawkSearch" @click="search()">搜索</el-button>
        <el-button plain @click="clearSearchData()">重置</el-button>
      </el-col>
      <el-col :span="4"
              style="float: right; text-align: right; padding-right: 30px">
        <el-button type="hawkCreate" @click="addRow()">创建主机</el-button>
      </el-col>
    </el-row>
    <hawk-table :table-data="tableData" :number="true"
                v-model="multipleSelection" :options="[
        { key: 'host', label: '主机名称',width:'170' },
        { key: 'name', label: '主机别名',width:'170' },
        { key: 'ip', label: 'IP' ,width:'170'},
        { key: 'itemCount', label: '监控项',width:'100' },
        { key: 'triggerCount', label: '触发器',width:'100' },
        { key: 'handle', label: '操作' },
      ]">
      <template #itemCount="{ row }">
        <span class="hawk-text-btn" :style="{padding:'0 15px', cursor:'point'}"
              @click="$router.push({name:'item',params:{row}})">{{ row.itemCount }}</span>
      </template>

      <template #triggerCount="{ row }">
        <span class="hawk-text-btn" :style="{padding:'0 15px', cursor:'point'}"
              @click="goToTrigger(row)">{{ row.triggerCount }}</span>
      </template>

      <template #monitorLength="{ row }">
        <span class="hawk-text-btn"
              @click="goMonitor(row.id)">{{row.monitorLength}}</span>
      </template>
      <template #triggerLenght="{ row }">
        <span class="hawk-text-btn"
              @click="goTrigger(row.id)">{{row.monitorLength}}</span>
      </template>
      <template #handle="{ row }">
        <span class="hawk-text-btn" @click="setAlarm(row)">告警配置</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="deleteAlarmConf(row)">删除告警配置</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="editRow(row)">编辑</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="delRow(row)">删除</span>
      </template>
    </hawk-table>
    <!-- 分页/多选操作 -->
    <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">{{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click="batchDelete()">批量删除</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryInfo.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryInfo.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div>
    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="formTitle" :visible.sync="showEditForm" width="50%"
               :close-on-click-modal="false" @close="closeEditForm">

      <el-form :model="editData" :rules="editRules" ref="editRef"
               label-width="100px">
        <el-form-item label="主机名称" prop="host">
          <el-input v-model="editData.host" placeholder="请输入主机名称,必须是英文和数字">
          </el-input>
        </el-form-item>

        <el-form-item label="主机别名" prop="name">
          <el-input v-model="editData.name" placeholder="请输入主机别名,不能有特殊字符">
          </el-input>
        </el-form-item>

        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="editData.ip"></el-input>
        </el-form-item>

        <div v-if="editData.itemCount>0"
             :style="{color:'red',textAlign:'center',fontSize:'13px'}">
          此接口有监控项，不能修改</div>
        <el-row>
          <el-col :span="11">
            <!-- <span>IP地址：</span> -->
            <el-form-item label="主机接口" prop="interface-ip">
              <el-input v-model="editData.interfaces[0].ip"
                        :disabled="editData.itemCount>0" placeholder="主机接口IP">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <!-- <span>端口：</span> -->
            <el-form-item label="端口" prop="interface-port">
              <!-- <label class="el-form-item__label" style="width:100px">端口</label> -->
              <el-input v-model="editData.interfaces[0].port" label="端口"
                        :disabled="editData.itemCount>0"
                        placeholder="与主机服务器通信端口" style="width:220px;">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="11">
            <el-form-item label="主机类型" prop="type">
              <el-select clearable v-model="editData.type"
                         placeholder="请选择主机类型">
                <el-option key="1" label="物理机" value="物理机"></el-option>
                <el-option key="2" label="虚拟机" value="虚拟机"></el-option>
                <el-option key="3" label="docker" value="docker"></el-option>
                <el-option key="4" label="未知" value="未知"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="是否为数据库">
              <el-radio v-model="editData.isDatabase" label="0" value="0">是
              </el-radio>
              <el-radio v-model="editData.isDatabase" label="1" value="1">否
              </el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="11">
            <el-form-item label="所属公司" prop="companyid">
              <el-select clearable v-model="editData.companyid"
                         placeholder="请选择所属部门">

                <el-option v-for="item in companyList" :key="item.id"
                           :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="所属部门" prop="departmentid">
              <el-select clearable v-model="editData.departmentid"
                         placeholder="请选择所属部门">

                <el-option v-for="item in departmentList" :key="item.id"
                           :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="所属机房" prop="computerroomid">
              <el-select clearable v-model="editData.computerroomid"
                         placeholder="请选择所属部门">

                <el-option v-for="item in computeroomList" :key="item.id"
                           :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="负责人" prop="userid">
              <el-select clearable v-model="editData.userid"
                         placeholder="请选择负责人">

                <el-option v-for="item in peopleList" :key="item.id"
                           :label="item.nickName" :value="item.id">
                  <!-- <span style="float: left">{{ item.name }}</span>
              <span
                    style="float: right; color: #8492a6; font-size: 13px">{{ item.telphone }}</span> -->
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item label="所属机柜" prop="cabinetid">
          <el-select clearable  v-model="editData.cabinetid" placeholder="请选择所属机柜">
            <el-option v-for="item in cabinetList" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->

        <!-- editData.type == 2 || editData.type == 3 -->
        <!-- 如果是虚拟机，有所属主机，如果是物理机，此项禁用 -->

        <el-row>
          <el-col :span="11">
            <el-form-item label="所属主机">
              <el-select clearable v-model="editData.installid"
                         placeholder="请选择安装的主机">
                <!-- <el-option-group v-for="group in hostList" :key="group.label"
                             :label="group.label"> -->
                <el-option v-for="item in  tableData" :key="item.host"
                           :label="item.host" :value="item.hostid">
                </el-option>
                <!-- </el-option-group> -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="模板" prop="selectedTemplateId">
              <el-select clearable v-model="selectedTemplateId"
                         placeholder="请选择模板">
                <!-- 调用模板列表 -->
                <el-option v-for="item in templateList" :key="item.templateid"
                           :label="item.name" :value="item.templateid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="DNS" prop="dns">
              <el-input v-model="editData.dns"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="网关" prop="gateway">
              <el-input v-model="editData.gateway"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="子网掩码" prop="subnet">
              <el-input v-model="editData.subnet"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="MAC地址" prop="macAddress">
              <el-input v-model="editData.macAddress"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditForm = false">取 消</el-button>
        <el-button type="primary" @click="saveData()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 告警配置 -->
    <el-dialog title="告警配置" :visible.sync="showAlarmForm"
               :close-on-click-modal="false" @close="closeAlarm">
      <el-form :model="alarmData" :rules="alarmRules" ref="alarmRef"
               label-width="100px" label-position="right">

        <el-form-item label="告警分组" prop="alarmGroupIds">
          <el-select v-model="alarmData.alarmGroupIds" multiple
                     placeholder="请选择告警分组">
            <el-option v-for="item in alarmGroupList" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="告警用户">
          <el-select v-model="alarmData.userIds" multiple placeholder="请选择告警用户">
            <el-option v-for="item in alarmPeopleList" :key="item.id"
                       :label="item.nickName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-row>

          <el-col :span="12">
            <el-form-item label="告警间隔" prop="delay">
              <el-input type="number" :min="1" v-model.number="alarmData.delay"
                        placeholder="告警间隔"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="间隔单位" prop="unit">
              <el-select clearable v-model="alarmData.unit" placeholder="单位">
                <!-- <el-option key="s" label="秒" value="s"></el-option> -->
                <el-option key="m" label="分钟" value="m"></el-option>
                <el-option key="h" label="小时" value="h"></el-option>
                <el-option key="d" label="天" value="d"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="告警次数" prop="count">
          <el-input type="number" :min="1" v-model.number="alarmData.count"
                    placeholder="请输入告警次数"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAlarmForm = false">取 消</el-button>
        <el-button type="primary" @click="saveAlarm()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="alarmDialogVisible" width="30%">
      <span>{{warnInfo}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="alarmDialogVisible = false">确 定
        </el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
/**
 * @author 罗冲
 * @description 监控配置下主机列表
 * @api 后台接口地址
 * @since 2021-11-08
 * @update 代码更新时间
 * @modifier 修改人
 * @bug 无
 * @version 版本号 例:v1.0.0
 */

// import { searchAlarm, addAlarm, editAlarm } from '@/api/monitor/config/business/index.js'

import {
  getList,
  addAlarm,
  getHostInterface,
  getHostDetail,
  deleteAlarm,
  getHostAlarm,
  doAdd,
  doEdit,
  doDelete,
  queryHostBus,
  isHostExists,
} from '@/api/monitor/config/host/index.js'

// import { getList as groupList } from "@/api/monitor/config/group"
import { getList as groupList, getAllUser } from '@/api/monitor/config/group'

import { getAll as userList } from '@/api/system/user'

import {
  getAllCompany, // 获得所有公司，没用到
} from '@/api/assets/dictionaries/company'

import { getDepartByComId } from '@/api/assets/dictionaries/department'

import { queryComputerRoom } from '@/api/assets/list/computerRoom'

import { getList as queryCabinetList } from '@/api/assets/list/cabinet'

import { getList as getAssetsHostList } from '@/api/assets/list/host' // 查询所属主机

import { getList as getTemplateList } from '@/api/monitor/config/template'

const IP_REG = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/

export default {
  data () {
    let isNameHave = async (rule, val, callback) => {
      let ret = await isHostExists({
        name: val,
      })
      console.log(ret)
      // console.log(ret.data);
      if (ret.code == 998) {
        callback()
      } else {
        callback(new Error('名称已存在'))
      }
    }

    let isHostHave = async (rule, val, callback) => {
      let ret = await isHostExists({
        host: val,
      })
      console.log(ret)
      if (ret.code == 998) {
        callback()
      } else {
        callback(new Error('名称已存在'))
      }
    }

    let interfacePort = (rule, value, callback) => {
      value = this.editData.interfaces[0].port.trim()
      if (value.length == 0) {
        callback('请输入端口')
        return
      }
      if (!/^\d+$/.test(value)) {
        callback('端口只能是数字')
        return
      }

      let inputPort = parseInt(value)
      if (inputPort < 0 || inputPort > 65535) {
        callback(new Error('端口是 1 -- 65535 之间的数字'))
      } else {
        callback()
      }
      if (inputPort < 0 || inputPort > 65535 || isNaN(inputPort)) {
        callback(new Error('端口范围 1 -- 65535'))
      } else {
        callback()
      }
    }

    let checkInterfaceIp = (rule, value, callback) => {
      value = this.editData.interfaces[0].ip.trim()
      if (value.trim().length == 0) {
        callback('请输入IP')
        return
      }

      if (IP_REG.test(value)) {
        callback()
      } else {
        callback('IP地址格式不正确')
      }
    }

    return {

      warnInfo: '当前主机属于业务系统，请从业务系统配置告警',

      oldTempId: 0, // 判断编辑时，模板ID 是否变化

      alarmDialogVisible: false,

      selectedTemplateId: '',
      // 表格数据
      tableData: [],
      // 提交信息
      queryInfo: {
        query: {
          name: '',
        },
        page: {
          current: 1,
          size: 10,
        },
      },
      // 数据总量
      total: 0,
      // 多选数据
      multipleSelection: [],
      // 显示添加/编辑
      showEditForm: false,
      // 添加编辑标题
      formTitle: '',
      // 添加编辑数据
      editData: {
        hostid: '', // 添加成功才会有 ID 值

        computerroomid: '', // 机房
        companyid: '', // 所属公司 ID
        departmentid: '',
        name: '', // 显示名称
        cabinetid: '', // 机柜ID
        userid: '', // 负责人

        installid: '', // 所属主机 ID

        host: '', // 主机名称
        interfaces: [
          {
            ip: '',
            port: '',
            type: 1,
            main: 1,
            useip: 1,
            dns: '',
          },
        ],

        templates: [
          // { templateid: '' } // 模板ID
        ],

        ip: '',
        isDatabase: '1',

        type: '', // 主机类型

        dns: '',
        gateway: '',
        subnet: '', // 子网掩码

        macAddress: '',

        itemCount: 0,
      },
      // 添加编辑验证
      editRules: {
        host: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { validator: isNameHave, trigger: 'blur' },
          {
            pattern: /^[.|a-z|A-Z|0-9|-]+$/,
            message: '只能是字母 数字 - .',
            trigger: 'blur',
          },
          { validator: isHostHave, trigger: 'blur' },
        ],

        name: [
          { required: true, message: '请输入主机别名', trigger: 'blur' },
          { validator: isNameHave, trigger: 'blur' },
        ],

        'interface-ip': [
          { required: true, validator: checkInterfaceIp, trigger: 'blur' },
        ],

        'interface-port': [
          { required: true, validator: interfacePort, trigger: 'blur' },
        ],

        ip: [
          { required: true, message: '请输入IP地址', trigger: 'blur' },
          { pattern: IP_REG, message: 'IP地址格式不正确', trigger: 'blur' },
        ],

        type: [{ required: true, message: '请选择主机类型', trigger: 'blur' }],

        companyid: [
          { required: true, message: '请选择所属公司', trigger: 'blur' },
        ],
        departmentid: [
          { required: true, message: '请选择所属部门', trigger: 'blur' },
        ],
        computerroomid: [
          { required: true, message: '请选择所属机房', trigger: 'blur' },
        ],

        installid: [
          { required: false, message: '请选择所属主机', trigger: 'blur' },
        ],
        userid: [{ required: true, message: '请选择负责人', trigger: 'blur' }],
        dns: [
          { required: true, message: '请输入DNS', trigger: 'blur' },
          { pattern: IP_REG, message: 'IP地址格式不正确', trigger: 'blur' },
        ],
        gateway: [
          { required: true, message: '请输入网关地址', trigger: 'blur' },
          { pattern: IP_REG, message: 'IP地址格式不正确', trigger: 'blur' },
        ],
        subnet: [
          { required: true, message: '请输入子网掩码', trigger: 'blur' },
          { pattern: IP_REG, message: 'IP地址格式不正确', trigger: 'blur' },
        ],
        macAddress: [
          { required: true, message: '请输入MAC地址', trigger: 'blur' },
        ],
      },
      // 主机列表
      hostList: [],

      companyList: [], // 所有公司

      computeroomList: [], // 机房列表
      // 公司/部门列表
      departmentList: [
        // 当前所选公司下的部门
      ],
      // 机房机柜列表
      cabinetList: [
        // 当前部门下的机柜 ID
      ],
      // 负责人列表
      peopleList: [],
      // 模板列表
      templateList: [],
      // 显示告警配置
      showAlarmForm: false,
      alarmData: {
        id: '',
        userIds: [],
        alarmGroupIds: [],
        delay: '',
        unit: '',
        count: '',
        hostid: '',
      },
      alarmRules: {
        delay: [{ required: true, message: '请输入告警间隔', trigger: 'blur' }],
        unit: [{ required: true, message: '请选择单位', trigger: 'blur' }],
        count: [{ required: true, message: '请输入告警次数', trigger: 'blur' }],
        // alarmGroupIds: [{ tyep:'array', required: true, message: '请输入告警次数', trigger: 'blur' }],
      },
      // 告警分组列表
      alarmGroupList: [],
      // 告警用户列表
      alarmPeopleList: [],

      // 第一次编辑时，不修改关联下拉框中的内容
      isFirstEdit: false,
    }
  },
  computed: {
    // 是否必须选择 安装在哪台主机
    isInstallIdMust () {
      return this.editData.type == '虚拟机' || this.editData.type == 'docker'
    },
  },
  watch: {
    'editData.companyid': {
      // 所选择公司发生改变时
      async handler (newValue, oldValue) {
        console.log(newValue)
        // 根据公司，获得该公司的部门
        if (!newValue){
          this.editData.departmentid=''
          this.departmentList=[]
          this.editData.computerroomid=''
          this.computeroomList=[]
          this.editData.userid=''
          this.peopleList=[]

           return
        }

        if (this.isFirstEdit) {
          return
        }

        const data = await getDepartByComId(newValue)
        console.log(data)

        this.departmentList = data.data

        this.editData.departmentid = ''
        this.editData.computerroomid = ''
        this.editData.computerroomid = ''
        this.editData.userid = ''
      },
    },
    // 部门换了，找机房
    'editData.departmentid': {
      async handler (newValue, oldValue) {
        console.log(newValue)
        // 根据公司，获得该公司的部门
        if (!newValue){
          this.editData.computerroomid=''
          this.computeroomList=[]
          this.editData.userid=''
          this.peopleList=[]

           return
        }

        if (this.isFirstEdit) {
          return
        }

        // 多条件查询机房
        const data = await queryComputerRoom({
          page: {
            current: 1,
            size: 1000,
          },
          query: {
            computeRoomName: '',
            companyId: this.editData.companyid,
            deptId: this.editData.departmentid,
            // areaId: this.queryAreaId(this.addForm.companyid),
            areaId: '',
            principalName: '', // 接口有需要，但页面中没有输入的地方
          },
        })
        this.computeroomList = data.data.records
        this.editData.computerroomid = ''
        this.editData.userid = ''
      },
    },

    // 机房变了，找机柜
    // "editData.computerroomid":{
    //  async handler (newValue, oldValue) {
    //     console.log(newValue);
    //     // 根据公司，获得该公司的部门
    //     if (!newValue) return
    //     // 多条件查询机房
    //     const data = await queryCabinetList({
    //       page: {
    //         current: 1,
    //         size: 1000
    //       },
    //       query: {
    //         computerroomid: this.editData.computerroomid,
    //         compayid: this.editData.companyid,
    //         departmentid: this.editData.departmentid,
    //       },
    //     })

    //     this.cabinetList = data.data.records
    //     this.editData.cabinetid = ''
    //   }
    // },

    'editData.computerroomid': {
      async handler (newValue, oldValue) {
        // 根据公司，获得该公司的部门
        if (!newValue){
          this.editData.userid=''
          this.peopleList=[]

           return
        }
        // 多条件查询机房
        if (this.isFirstEdit) {
          return
        }

        console.log('---------isEdit-----------')

        let room = this.computeroomList.find((item) => {
          return (item.id = this.editData.computerroomid)
        })
        // 目前一个机房只有一个管理员，如果将来增加再说。
        this.peopleList = [room.sysUser]
        console.log(this.peopleList)
      },
    },

    selectedTemplateId: {
      async handler (newValue, oldValue) {
        // 根据公司，获得该公司的部门
        if (!newValue) return
        // 多条件查询机房
        // if (this.isFirstEdit) {
        //   return
        // }

        let temItem = this.templateList.find((item) => {
          return item.templateid == newValue
        })
        if (temItem) {
          console.log(temItem, '---------所选模板--')
          this.editData.templates = [temItem]
        } else {
          console.warn('没有找到模板')
        }
      },
    },
  },


  methods: {



    showWarn (msg) {
      this.warnInfo = msg;
      this.alarmDialogVisible = true
    },

    goToTrigger (row) {
      if (row.itemCount > 0) {
        this.$router.push({ name: 'trigger', params: { row } })
      } else {
        this.showWarn('请先配置监控项')
      }

    },

    queryAreaId (compayid) {
      let c = this.companyList.find((it) => {
        return compayid == it.id
      })
      return c.areaId
    },

    // 相当于 init 
    async getHostList () {
      const ret = await getList(this.queryInfo)
      console.log(ret, '-----init 中 获得所有主机信息----------')
      if (ret && ret.code == 20000) {
        let data = ret.data
        this.tableData = data.records
        this.total = data.total
      }

      // 获得所有主机

      const { data } = await getAssetsHostList({
        query: {
          name: '', // 主机名
          principal: '', // 	负责人名称
          ip: '', //
          businessname: '',
        },
        page: {
          current: 1,
          size: 100,
        },
      })

      // console.log(data, '---主机列表')
      this.hostList = data.records
      // this.total = data.total

    },
    // 新增
    addRow () {
      this.showEditForm = true
      this.formTitle = '新增主机'
    },

    // 编辑
    async editRow (row) {
      console.log(row);
      
      console.log(row)

      this.formTitle = '编辑主机'

      this.isFirstEdit = true

      // 根据主机ID 获得主机详细信息
      // 获得所有部门
      const ret22 = await getDepartByComId(row.companyid)
      console.log(ret22)
      this.departmentList = ret22.data

      // 多条件查询机房
      const ret = await queryComputerRoom({
        page: {
          current: 1,
          size: 1000,
        },
        query: {
          computeRoomName: '',
          companyId: this.editData.companyid,
          deptId: this.editData.departmentid,
          // areaId: this.queryAreaId(this.addForm.companyid),
          areaId: '',
          principalName: '', // 接口有需要，但页面中没有输入的地方
        },
      })
      this.computeroomList = ret.data.records
      console.log(this.computeroomList)
      console.log(row.computerroomid)
      // 根据 机房查询 人员
      let room = this.computeroomList.find((item) => {
        return (item.id = row.computerroomid)
      })
      console.log(room)
      // 目前一个机房只有一个管理员，如果将来增加再说。
      if (room) {
        this.peopleList = [room.sysUser]
      }
      console.log(this.peopleList)
      // this.editData.userid=''

      // this.editData = Object.assign({}, row);

      Object.assign(this.editData, row)

      // 检查是否有 interface 和 template 如果没有，再获取
      if (!this.editData.interfaces) {
        this.editData.interfaces = [{}]
        this.editData.interfaces[0].ip = ''
        this.editData.interfaces[0].port = ''

        // 根据主机，获得接口
        let ret = await getHostInterface(row.hostid)
        if (ret.code == 20000) {
          this.editData.interfaces = ret.data
        }
      }

      if (!this.editData.templates) {
        this.editData.templates = [{}]
        this.editData.templates[0].id = ''

        let ret = await getHostDetail(row.hostid)

        console.log(ret, '-----根据ID 获得详情--------')
        console.log(this.editData)

        this.itemCount = ret.itemCount

        if (ret.code == 20000 && ret.data.templates.length > 0) {
          this.editData.templates = ret.data.templates
          this.selectedTemplateId = this.editData.templates[0].templateid
        }
      } else {
        this.selectedTemplateId = this.editData.templates[0].templateid
      }

      this.showEditForm = true

      this.editData.isDatabase = '' + this.editData.isDatabase

      setTimeout(() => {
        this.isFirstEdit = false
      }, 1000)

      // 保存当前模板 ID
      this.oldTempId = this.editData.templates[0].templateid
    },
    // 搜索
    search () {
      console.log(this.queryInfo)
      this.getHostList()
    },
    // 重置搜索
    clearSearchData () {
      this.queryInfo = this.$options.data().queryInfo
      this.getHostList()
    },
    // 改变页码
    handleCurrentChange (val) {
      this.queryInfo.page.current = val
      this.getHostList()
    },
    // 改变数量
    handleSizeChange (val) {
      this.queryInfo.page.size = val
      this.getHostList()
    },
    // 删除
    async delRow (row) {
      console.log(row)

      this.$confirm(`确定删除主机${row.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let ret = await doDelete([row.hostid])

          if (ret.code == 20000) {

            let type = ''
            if (ret.data || ret.message.indexOf('成功') != -1) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }

            this.$message({
              type: type,
              message: ret.message,
            })

            if (this.tableData.length == 1) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []

            //清空选择框
            this.getHostList()

          }


        })
        .catch(() => { })
    },
    // 多选
    handleSelectionChange (val) {
      console.log(val)
      this.multipleSelection = val
    },
    // 批量删除
    async batchDelete () {
      if (this.multipleSelection.length < 1) {
        this.$message({
          type: 'warning',
          message: '请选择需要删除的数据',
        })
        return
      } else {

        let idList = []
        for (let i = 0; i < this.multipleSelection.length; i++) {
          idList.push(this.multipleSelection[i].hostid)
        }
        console.log(idList)
        let ret = await doDelete(idList)
        console.log(ret, '--------------ret----');

        if (ret.code == 20000) {

          let type = ''
          if (ret.data || ret.message.indexOf('成功') != -1) {
            ret.message = '删除成功'
            type = 'success'
          } else {
            type = 'error'
          }

          this.$message({
            type: type,
            message: ret.message,
          })

          // console.log(this.multipleSelection.length);
          if (this.multipleSelection.length == this.tableData.length) {
            this.queryForm.page.current = this.queryForm.page.current - 1
            if (this.queryForm.page.current < 1) {
              this.queryForm.page.current = 1
            }
          }

          console.log('-------------init---');
        }

        //清空选择框
        this.multipleSelection = []
        setTimeout(() => {
          this.getHostList()
        }, 200);
      }
    },
    // 新增/编辑提交
    async saveData () {
      console.log('--------11111---')
      this.$refs['editRef'].validate(async (valid) => {
        console.log(valid)

        if (!valid) return

        console.log(this.editData)
        console.log(this.editData.templates.length)
        if (this.editData.templates.length == 0) {
          // 没有模板
          this.editData.ischangeTemp = 0 // 没有修改
        } else {
          if (this.oldTempId == this.editData.templates[0].templateid) {
            this.editData.ischangeTemp = 0 // 没有修改
          } else {
            this.editData.ischangeTemp = 1 // 修改
          }
        }

        if (this.editData.hostid) {
          let ret = await doEdit(this.editData)
          console.log(ret)
          if (ret.code === 20000) {
            // 清空临时保存的数据
            this.selectedTemplateId = ''
            this.$message({
              type: 'success',
              message: '主机更新成功',
            })
          }
        } else {
          let ret = await doAdd(this.editData)
          console.log(ret)
          if (ret.code === 20000) {
            // 清空临时保存的数据
            this.selectedTemplateId = ''
            this.$message({
              type: 'success',
              message: '主机创建成功',
            })
          }
        }
        this.showEditForm = false

        this.getHostList()
      })
    },
    // 关闭添加/编辑弹窗
    closeEditForm () {
      this.editData = this.$options.data().editData
      this.$refs.editRef.resetFields() //重置表单校验方法
      this.showEditForm = false
      this.selectedTemplateId = ''
    },

    deleteAlarmConf (row) {
      this.$confirm(`确认删除?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async () => {
        let ret = deleteAlarm(row.hostid)
        if (ret.code == 20000) {
          this.$msg({
            type: 'success',
            message: '删除成功',
          })
        }
      })

      this.getHostList()
    },

    // 显示告警配置
    async setAlarm (row) {

      let ret1 = await queryHostBus(row.hostid)

      console.log(ret1)

      if (ret1.code !== 998) {
        this.alarmDialogVisible = true
        return
      }

      // 清空数据
      this.alarmData = this.$options.data().alarmData

      console.log(this.alarmData)

      this.formTitle = '告警配置'
      let ret = await getHostAlarm(row.hostid, 2)
      console.log(ret)


      if (ret.code == 20000 && ret.data) {
        this.alarmData = ret.data

        if (ret.data.alarmGroups.length > 0) {
          this.alarmData.alarmGroupIds = ret.data.alarmGroups.map((el) => el.id)
          console.log(this.alarmData.alarmGroupIds)
        } else {
          this.alarmData.alarmGroupIds = []
        }

        if (ret.data.users.length > 0) {
          this.alarmData.userIds = ret.data.users.map((el) => el.id)
        } else {
          this.alarmData.userIds = []
        }
      }

      this.alarmData.hostid = row.hostid

      this.showAlarmForm = true
    },
    // 提交告警配置
    saveAlarm () {

      if (this.alarmData.alarmGroupIds == null) {
        this.alarmData.alarmGroupIds = []
      }

      if (this.alarmData.userIds == null) {
        this.alarmData.userIds = []
      }

      this.$refs.alarmRef.validate(async (valid) => {
        if (!valid) return

        if (this.alarmData.userIds.length < 1 &&
          this.alarmData.alarmGroupIds.length < 1) {

          this.$message({
            type: 'warning',
            message: '告警分组与告警用户不可都为空',
          })
          return
        }
        //判断告警间隔或告警次数不为负数或0
        if (this.alarmData.delay < 1 || this.alarmData.count < 1) {
          this.$message({
            type: 'warning',
            message: '告警间隔或告警次数输入不可为0或负数',
          })
          return
        }

        console.log(this.alarmData.delay, '-------添加的告警信息-------')
        console.log(this.alarmData, '-------添加的告警信息-------')
        //调用方法
        // if (this.alarmData.id) {
        //告警配置修改
        // await editAlarm(this.alarmData)
        // } else {
        //告警配置新增
        let ret = await addAlarm(this.alarmData)
        console.log(ret)

        // }
        this.showAlarmForm = false
      })

      this.getHostList()
    },
    // 关闭告警配置弹窗
    closeAlarm () {
      this.editData = this.$options.data().editData
      this.$refs.alarmRef.resetFields() //重置表单校验方法
      this.showAlarmForm = false
    },
    // 跳转到监控项
    goMonitor (id, interfaceId) {
      console.log(interfaceId)
      this.$router.push({
        name: 'item',
        params: { id: id, interfaceId: interfaceId, type: 0 },
      })
    },
    // 跳转到触发器
    goTrigger (id, host) {
      console.log(id)
      this.$router.push({
        name: 'trigger',
        params: { id: id, name: host, type: 0 },
      })
    },
  },
  async created () {
    this.getHostList()
    // this.alarmGroupList = await groupList()
    // this.alarmPeopleList = await userList()

    // 获得所有的公司
    let ret = await getAllCompany()
    console.log(ret, '---------getAllCompany---------')
    if (ret.code == 20000) {
      this.companyList = ret.data
    }



    // 所有模板
    const res = await getTemplateList({
      query: {
        host: '',
      },
      page: {
        current: 1,
        size: 100,
      },
    })
    console.log(res, '-------------获得所有模板--------')
    if (res.code == 20000) {
      this.templateList = res.data.records
    }

    // 所有告警分组
    groupList({
      query: {
        name: '',
      },
      page: {
        current: 1,
        size: 1000,
      },
    }).then((ret) => {
      console.log(ret, '----警告分组信息')
      this.alarmGroupList = ret.data.records
    })
    // this.alarmPeopleList = await userList()
    // console.log(this.alarmGroupList, "分组")

    // 所有用户
    getAllUser().then((ret) => {
      console.log(ret, '---------所有的用户')
      if (ret.code == 20000) {
        this.alarmPeopleList = ret.data
      }
    })


  },
}
</script>

<style lang='scss' scoped>
</style>